package org.jfk.sys.dictionary;

import java.util.List;

import org.apache.log4j.Logger;
import org.jfk.core.model.SqlFilter;
import org.jfk.sys.user.User;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

@SuppressWarnings("serial")
public class Dict extends Model<Dict>{
	private static Logger logger = Logger.getLogger(Dict.class);	
	public static final Dict dao;
	public static final Table table;
	public static final String tableName;
	static {
		dao = new Dict();
		table = TableMapping.me().getTable(Dict.class);
		tableName = table.getName();
	}
	public Dict findById(Object id){
		return dao.findFirst("select a.*,b.loginName creator_loginName,c.cnName dict_type_cnName"
				+ " from "+tableName+" a left outer join "+User.tableName+" b on a.creator=b.id"
				+ " left outer join "+DictType.tableName+" c on a.dict_type=c.id"
				+ " where a.id=?",id);
	}	

	public Page<Dict> paginate(DictController controller){
		String select = " select "+tableName+".*,ot1.loginName creator_loginName,ot2.cnName dict_type_cnName";
		String from =" from "+tableName;
		String join = " left outer join "+User.tableName+" ot1 on ot1.id="+tableName+".creator";
		join = join + " left outer join "+DictType.tableName+" ot2 on ot2.id="+tableName+".dict_type";
		String where = " where 1=1 ";
		
		SqlFilter filter = controller.genJsonFilter();
		
		//处理列表查询的智能搜索
		String search = controller.getPara("search");	

		if (search != null && !"".equals(search.trim())) {
			SqlFilter searchFilter = new SqlFilter();
			searchFilter.add("and", tableName+".id", "eq", search);
			searchFilter.add("or", tableName+"dict_value", "like", search);
			searchFilter.add("or", tableName+".description", "like", search);
			searchFilter.end();
			filter.add(searchFilter);
			controller.setAttr("search", search);
		}
		
		controller.addPageAttr();
		String sqlExceptSelect = from+join+where+filter.sqlText;
		sqlExceptSelect = sqlExceptSelect + controller.sqlSort;
		logger.debug(filter);
		Page<Dict> page = dao.paginate(controller.currentPage, controller.limit, select, sqlExceptSelect, filter.params.toArray());
		return page;		
	}	
	
	public List<Dict> queryDictByTypeName(String dictType){
		return Dict.dao.find("select a.* from "+tableName+" a,"+DictType.tableName+" b where a.dict_type = b.id and b.enName = ? order by showOrder", dictType);
	}

	public List<Dict> queryDictByTypeId(Object dictType){
		return Dict.dao.find("select a.* from "+tableName+" a where a.dict_type = ?", dictType);
	}
	
}
